<?php
// https://m.bhz360.com/index2.php?route=ssl/login
class ControllerSslLogin extends Controller {
    private $_APPID = 'wx8cdac7431d56c5f4';
    private $_APPSECRET = 'c9bbeea4e83a0d8489f165573dd6772a';

    public function index() {
        $name = trim($this->request->get['name']);
        $pass = trim($this->request->get['pass']);
        $code = trim($this->request->get['code']);
        $wxAppOpenId = $this->_getOpenIdByCode($code);
        $ret = array(
            'status' => false,
            'message' => '用户绑定失败',
        );
        if ('' != $name && '' != $pass && '' != $wxAppOpenId) {
            if ($customerId = $this->_loginCheck($name, $pass)) {
                $this->load->model('ssl/customer');
                $this->_userbind($customerId, $wxAppOpenId);
                $ret = array(
                    'status' => true,
                    'wxAppOpenId'=>$wxAppOpenId,
                    'message' => '用户绑定成功',
                    'info' => $this->model_ssl_customer->bindCheck($wxAppOpenId),
                );
            }
        }
        die(json_encode($ret));
    }

    public function bindCheck() {
        $code = trim($this->request->get['code']);
        $lat = isset($this->request->get['lat'])?trim($this->request->get['lat']):'';
        $long = isset($this->request->get['long'])?trim($this->request->get['long']):'';
        if(!empty($lat)&&!empty($long)){
            $latlong=$this->latlong($lat,$long);
            $this->load->model('wxapp/point');
           $sql=$this->model_wxapp_point->latlong($latlong);
           //print_r($sql);die;
            foreach ($sql as $key => $value) {
                $arr[$value['shop_id']]=$this->getDistance($lat,$long,$value['lat'],$value['lng']);
            }
            //找离用户最近的商铺的id
                $pos = array_search(min($arr), $arr);
        }
        $wxAppOpenId = $this->_getOpenIdByCode($code);
        $ret = array(
            'status' => false,
            'message' => '用户信息获取失败！',
        );
        if ('' != $wxAppOpenId) {
            $customerInfo = $this->_bindCheck($wxAppOpenId,$pos);
            if ($customerInfo['customerId']) {
                $message = '店长 / 业务员登录';
            }else{
                $message = '终端客户登录';
            }
            $ret = array(
                'status' => true,
                'message' => $message,
                'info' => $customerInfo,
            );
        }
        die(json_encode($ret));
    }

    public function accessToken() {
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_APPID.'&secret='.$this->_APPSECRET;
        //var_dump($url);
        die(file_get_contents($url));
    }

    public function customerInShopUpdate() {
        $pk = intval($this->request->get['pk']);
        $info = json_decode(htmlspecialchars_decode($this->request->get['info']), true);
        $this->load->model('ssl/customer');
        $this->model_ssl_customer->updateCustomerInShop($pk, $info);
        die();
    }

    public function shareSolutionToFriends() {
        $solutionId = intval($this->request->get['solutionId']);
        $AT = json_decode(file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->_APPID.'&secret='.$this->_APPSECRET), true);
        // $url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token='.$AT['access_token'];
        // $data = array(
        //     'path' => '/pages/customer/ai/shelf/shelf?solutionId='.$solutionId,
        //     'width' => '430',
        // );
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$AT['access_token'];
        $data = array(
            'scene'=>$solutionId,
            'page' => 'pages/customer/ai/shelf/shelf',
            'width' => 430
        );
        header('Content-Type: image/jpeg');
        echo $this->_myCurl($url, $data);
    }

    public function customerReviewCheck() {
        $pk = intval($this->request->get['pk']);
        $this->load->model('ssl/customer');
        $info = $this->model_ssl_customer->getByPK($pk);
        die(json_encode($info['need_review']));
    }

    protected function _myCurl($url, $data=array()){
        $c = curl_init();
        curl_setopt($c, CURLOPT_URL, urldecode($url));
        curl_setopt($c, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($c, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($c, CURLOPT_TIMEOUT,5);
        if (count($data)) {
            curl_setopt($c, CURLOPT_POST, 1);
            curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($data));
        }
        $pageSource = curl_exec($c);
        return $pageSource;
    }
    //获取微信openid
    protected function _getOpenIdByCode($code) {
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$this->_APPID.'&secret='.$this->_APPSECRET.'&js_code='.$code.'&grant_type=authorization_code';
        $ret = json_decode(file_get_contents($url));
        return $ret->openid;
    }

    protected function _loginCheck($name, $pass) {
        $this->load->model('ssl/customer');
        return $this->model_ssl_customer->loginCheck($name, $pass);//登录验证，失败返回false
    }

    protected function _userbind($customerId, $wxAppOpenId) {
        $this->load->model('ssl/customer');
        $this->model_ssl_customer->clearBind($wxAppOpenId);//移除之前的绑定
        $this->model_ssl_customer->userBind($customerId, $wxAppOpenId);//绑定新用户
    }
    //查openid是否在数据库判断是店长还是业务员还是c端用户
    protected function _bindCheck($wxAppOpenId,$shopid) {
        $this->load->model('ssl/customer');
        return $this->model_ssl_customer->bindCheck($wxAppOpenId,$shopid);//登录验证，失败返回false
    }
    //换算用户0.5km范围的经纬度
    public function latlong($latitude,$longitude){
         $r = 6371;//地球半径千米
         $dis = 0.5;//0.5千米距离
         $dlng =  2*asin(sin($dis/(2*$r))/cos($latitude*pi()/180));
         $dlng = $dlng*180/pi();//角度转为弧度
         $dlat = $dis/$r;
         $dlat= $dlat*180/pi();
         $arr['minlat'] =$latitude-$dlat;
         $arr['maxlat'] = $latitude+$dlat;
         $arr['minlng'] = $longitude-$dlng;
         $arr['maxlng'] = $longitude+$dlng;
         return $arr;
    }
    //离用户最近的几个商铺分辨实际距离
    function getDistance($lat1, $lng1, $lat2, $lng2) {
                    $earthRadius = 6367000; //approximate radius of earth in meters

                    $lat1 = ($lat1 * pi() ) / 180;
                    $lng1 = ($lng1 * pi() ) / 180;

                    $lat2 = ($lat2 * pi() ) / 180;
                    $lng2 = ($lng2 * pi() ) / 180;
                    $calcLongitude = $lng2 - $lng1;
                    $calcLatitude = $lat2 - $lat1;
                    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
                    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
                    $calculatedDistance = $earthRadius * $stepTwo;

                    return round($calculatedDistance);
     }


}
